//
//  KYLoginView.m
//  KYKJPackDemo
//
//  Created by Jordan zhou on 2017/9/28.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "KYLoginView.h"
#import "KYLoginButton.h"
#import "ReactiveCocoa.h"

@interface KYLoginView()
@property (nonatomic, weak) UIImageView *bgImgView;
@property (nonatomic, weak) UILabel *tipsLabel;
@property (nonatomic, weak) UILabel *accountLabel;
@property (nonatomic, weak) UITextField *phoneTf;
@property (nonatomic, weak) UIProgressView *phoneView;
@property (nonatomic, weak) UILabel *codeLabel;
@property (nonatomic, weak) UITextField *codeTf;
@property (nonatomic, weak) KYCodeButton *postCodeBtn;
@property (nonatomic, weak) UIProgressView *codeView;
@property (nonatomic, weak) KYLoginButton *loginBtn;

@end

@implementation KYLoginView

+ (instancetype)customLoginView {
    return [[self alloc] init];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        // 0.初始化所有子控件
        [self setUpSubViews];
        
        // 1.初始化登陆按钮
        [self setUpLoginBtnView];
    }
    
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        
        // 0.初始化所有子控件
        [self setUpSubViews];
        
        // 1.初始化登陆按钮
        [self setUpLoginBtnView];
    }
    
    return self;
}

- (void)setUpSubViews
{
    // 0.初始化控件
    UIImageView *bgImgView = [[UIImageView alloc] init];
    bgImgView.image = [UIImage imageWithName:@"loginBgImgView"];
    [self addSubview:bgImgView];
    self.bgImgView = bgImgView;
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    tipsLabel.text = NSLocalizedString(@"无需注册手机号一步登录", nil);
    tipsLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:tipsLabel];
    self.tipsLabel = tipsLabel;
    
    UILabel *accountLabel = [[UILabel alloc] init];
    accountLabel.text = NSLocalizedString(@"账 号:", nil);
    accountLabel.font = [UIFont boldSystemFontOfSize:16.5f];
    accountLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:accountLabel];
    self.accountLabel = accountLabel;
    
    UITextField *phoneTf = [[UITextField alloc] init];
    phoneTf.clearButtonMode = UITextFieldViewModeAlways;
    phoneTf.keyboardType = UIKeyboardTypeNumberPad;
    phoneTf.borderStyle = UITextBorderStyleNone;
    phoneTf.placeholder = NSLocalizedString(@"请输入手机号", nil);
    phoneTf.font = [UIFont systemFontOfSize:16.0f];
    [self addSubview:phoneTf];
    self.phoneTf = phoneTf;
    
    UIProgressView *phoneView = [[UIProgressView alloc] init];
    phoneView.backgroundColor = [UIColor colorWithHexString:@"#B6B6B6"];
    [self addSubview:phoneView];
    self.phoneView = phoneView;
    
    UILabel *codeLabel = [[UILabel alloc] init];
    codeLabel.text = NSLocalizedString(@"验证码:", nil);
    codeLabel.font = [UIFont boldSystemFontOfSize:16.5f];
    codeLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:codeLabel];
    self.codeLabel = codeLabel;
    
    UITextField *codeTf = [[UITextField alloc] init];
    codeTf.clearButtonMode = UITextFieldViewModeAlways;
    codeTf.keyboardType = UIKeyboardTypeNumberPad;
    codeTf.borderStyle = UITextBorderStyleNone;
    codeTf.placeholder = NSLocalizedString(@"请输入验证码", nil);
    codeTf.font = [UIFont systemFontOfSize:16.0f];
    [self addSubview:codeTf];
    self.codeTf = codeTf;
    
    KYCodeButton *postCodeBtn = [[KYCodeButton alloc] init];
    postCodeBtn.layer.cornerRadius = 2;
    postCodeBtn.layer.masksToBounds = YES;
    postCodeBtn.layer.borderWidth = 2;
    postCodeBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    postCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14.5f];
    [postCodeBtn setTitle:NSLocalizedString(@"发送验证码", nil) forState:UIControlStateNormal];
    [postCodeBtn setTitle:NSLocalizedString(@"发送验证码", nil) forState:UIControlStateHighlighted];
    [postCodeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [postCodeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [postCodeBtn addTarget:self action:@selector(postCodeBtnClick:) forControlEvents:UIControlEventTouchDown];
    postCodeBtn.tag = KYLoginViewPostCodeBtnType;
    [self addSubview:postCodeBtn];
    self.postCodeBtn = postCodeBtn;
    
    UIProgressView *codeView = [[UIProgressView alloc] init];
    codeView.backgroundColor = [UIColor colorWithHexString:@"#B6B6B6"];
    [self addSubview:codeView];
    self.codeView = codeView;
    
    // 1.注册通知
    [KYNotificationCenter addObserver:self selector:@selector(phoneTextDidChange) name:UITextFieldTextDidChangeNotification object:phoneTf];
    
    [KYNotificationCenter addObserver:self selector:@selector(codeTextDidChange) name:UITextFieldTextDidChangeNotification object:codeTf];
}

#pragma mark - 通知监听
- (void)phoneTextDidChange
{
    CGSize phoneTfSize = [self.phoneTf.text sizeWithAttributes:@{NSFontAttributeName : self.phoneTf.font}];
    float progress = phoneTfSize.width / self.phoneView.frame.size.width;
    
    if (self.phoneTf.text.length > 11) {
        self.phoneView.progressTintColor = [UIColor colorWithHexString:@"#D70000"];
    } else {
        self.phoneView.progressTintColor = KYColor(88, 184, 249, 1.0);
    }
    
    [self.phoneView setProgress:progress animated:YES];
}

- (void)codeTextDidChange
{
    CGSize codeTfSize = [self.codeTf.text sizeWithAttributes:@{NSFontAttributeName : self.codeTf.font}];
    float progress = codeTfSize.width / self.codeView.frame.size.width;
    
    if (self.codeTf.text.length > 6) {
        self.codeView.progressTintColor = [UIColor colorWithHexString:@"#D70000"];
    } else {
        self.codeView.progressTintColor = KYColor(88, 184, 249, 1.0);
    }
    
    [self.codeView setProgress:progress animated:YES];
}


- (void)setUpLoginBtnView
{
    [self endEditing:YES];
    
    // 0.避免block循环引用
    __weak typeof(self) selfVc = self;
    
    // 1.创建登陆按钮
    KYLoginButton *loginBtn = [[KYLoginButton alloc] initWithFrame:CGRectMake(45, 310, kScreenWidth - 90, 44)];
    [self addSubview:loginBtn];
    self.loginBtn = loginBtn;
    
    loginBtn.translateBlock = ^{
        if (![KYBaseDataTool isMobileNumber:self.phoneTf.text]) { // 先验证手机号
            [MBProgressHUD showLoginError:NSLocalizedString(@"请输入正确的手机号", nil)];
        } else {
#warning - OK 登录接口(通过代理传出去因为涉及控制器跳转)
            // 0.发送请求
            [JSTNewServer requestLoginWithPhoneNum:selfVc.phoneTf.text modifyCode:selfVc.codeTf.text success:^(NSDictionary *dataDict) {
                if ([dataDict[@"status"] isEqualToNumber:@1]) {
                    NSDictionary *dict = [dataDict objectForKey:@"data"];
                
                    KYLog(@"dict = %@",dict);

                    // 1.归档登录账户信息
                    [selfVc encoderUserInfo:dict];
                    
                    // 2.登录淘宝IM服务器
                    [kAppDelegate setupIM];
                    
                    // 3.页面退出
                    [[self ky_getCurrentViewController] dismissViewControllerAnimated:YES completion:nil];
                    
                } else {
                    [MBProgressHUD showError:@"登录失败"];
                }
                
            } failure:^(NSString *failureStr) {
                [MBProgressHUD showError:failureStr];
            }];
        }
    };
    
    // 2.运行时机制来监听登录按钮的可点击性
    [self setUpLoginBtnEnabel];
}

- (void)setUpLoginBtnEnabel
{
    // 运行时机制保证事实确认注册点击
    RACSignal *valid = [RACSignal combineLatest:@[self.phoneTf.rac_textSignal,self.codeTf.rac_textSignal] reduce:^(NSString *account,NSString *code){
        return @(account.length > 0 && code.length > 0);
    }];
    RAC(self.loginBtn,userInteractionEnabled) = valid;
}

- (void)encoderUserInfo:(NSDictionary *)dict
{
    // 0.要删除的归档
    [JSTSystemInfo cacheIphoneNum:[NSString stringWithFormat:@"%@",dict[@"username"]]];
    
    // 1.全新归档模式
    [KYUserAccountTool shareUserData].token = [dict objectForKey:@"token"];
    [KYUserAccountTool shareUserData].userPhone = [NSString stringWithFormat:@"%@",dict[@"username"]];
    [KYUserAccountTool shareUserData].taobaoKey = [NSString stringWithFormat:@"%@",dict[@"taobao_key"]];
    [KYUserAccountTool shareUserData].headImg = [NSString stringWithFormat:@"%@",dict[@"icon"]];
    [KYUserAccountTool shareUserData].userName = [NSString stringWithFormat:@"%@",dict[@"name"]];
    [KYUserAccountTool shareUserData].userSex = [NSString stringWithFormat:@"%@",dict[@"sex"]];
    [KYUserAccountTool shareUserData].userBirth = [NSString stringWithFormat:@"%@",dict[@"birth_month"]];
    [KYUserAccountTool shareUserData].userIntro = [NSString stringWithFormat:@"%@",dict[@"sign"]];
    [[KYUserAccountTool shareUserData] saveToSandBox];
}

- (void)postCodeBtnClick:(KYCodeButton *)btn
{
    __weak typeof (self) selfVc = self;
    
    if (![KYBaseDataTool isMobileNumber:self.phoneTf.text]) {
        [MBProgressHUD showError:NSLocalizedString(@"请填写正确手机号", nil)];
    } else {
#warning - OK 验证码接口(直接写在里面)
        // 1.发送请求
        /*
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"mobile"] = selfVc.phoneTf.text;
        params[@"apkname"] = [JSTSystemInfo applicationIdentifier];
        params[@"appkey"] = [JSTSystemInfo userKey];
        params[@"appname"] = [JSTSystemInfo applicationName];
        NSString *url = [NSString stringWithFormat:@"%@/%@", kAppServerForHttps, getMsgCodeUrl];
         */
        NSDictionary *params = @{@"mobile" : selfVc.phoneTf.text,
                                 @"apkname" : [KYSystemInfoTool bundleID],
                                 @"appkey" : [KYSystemInfoTool appKey],
                                 @"appname" : [KYSystemInfoTool appName]
                                 };
    
        NSString *url = [NSString stringWithFormat:@"%@/%@", kAppServerForHttps, getMsgCodeUrl];
        
        [KYNetTool getWithURL:url params:params success:^(id json) {
            
            // 2.时间改变
            [selfVc.postCodeBtn addToucheHandler:^(KYCodeButton *codeButton, NSInteger tag) {
                codeButton.enabled = NO;
                if ([codeButton startWithSecond:300] == YES) {
                    
                    // 3.已发送验证码并且通知代理
                    if ([selfVc.delegate respondsToSelector:@selector(loginView:didClickPostCodeButton:)]) {
                        [selfVc.delegate loginView:selfVc didClickPostCodeButton:btn];
                    }
                }
                [codeButton didChange:^NSString *(KYCodeButton *codeButton,int second) {
                    NSString *title = [NSString stringWithFormat:@"剩余%d秒",second];
                    return title;
                }];
                [codeButton didFinished:^NSString *(KYCodeButton *codeButton, int second) {
                    codeButton.enabled = YES;
                    return @"重新发送";
                }];
            }];

        } failure:^(NSError *error) {
            
        }];
    }
}

/**
 *  拿到真实的尺寸布局子控件
 */
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.bgImgView.frame = self.bounds;
    
    CGFloat tipsLabelX = 0;
    CGFloat tipsLabelY = 10;
    CGFloat tipsLabelW = self.frame.size.width;
    CGFloat tipsLabelH = 45;
    self.tipsLabel.frame = CGRectMake(tipsLabelX, tipsLabelY, tipsLabelW, tipsLabelH);
    
    CGFloat margin = 10;
    CGFloat accountLabelX = margin;
    CGFloat accountLabelY = CGRectGetMaxY(self.tipsLabel.frame) + 25;
    CGFloat accountLabelW = 60;
    CGFloat accountLabelH = 44;
    self.accountLabel.frame = CGRectMake(accountLabelX, accountLabelY, accountLabelW, accountLabelH);
    
    CGFloat phoneTfX = accountLabelX + accountLabelW;
    CGFloat phoneTfY = accountLabelY;
    CGFloat phoneTfW = self.frame.size.width - phoneTfX - margin;
    CGFloat phoneTfH = accountLabelH;
    self.phoneTf.frame = CGRectMake(phoneTfX, phoneTfY, phoneTfW, phoneTfH);
    
    CGFloat phoneViewX = phoneTfX;
    CGFloat phoneViewY = CGRectGetMaxY(self.phoneTf.frame);
    CGFloat phoneViewW = phoneTfW;
    CGFloat phoneViewH = 1;
    self.phoneView.frame = CGRectMake(phoneViewX, phoneViewY, phoneViewW, phoneViewH);
    
    CGFloat codeLabelX = accountLabelX;
    CGFloat codeLabelY = CGRectGetMaxY(self.phoneView.frame) + 30;
    CGFloat codeLabelW = accountLabelW;
    CGFloat codeLabelH = accountLabelH;
    self.codeLabel.frame = CGRectMake(codeLabelX, codeLabelY, codeLabelW, codeLabelH);

    CGFloat codeTfX = phoneTfX;
    CGFloat codeTfY = codeLabelY;
    CGFloat codeTfW = phoneTfW - 90;
    CGFloat codeTfH = phoneTfH;
    self.codeTf.frame = CGRectMake(codeTfX, codeTfY, codeTfW, codeTfH);
    
    CGFloat postCodeBtnW = 85;
    CGFloat postCodeBtnX = tipsLabelW - postCodeBtnW - margin;
    CGFloat postCodeBtnY = codeTfY;
    CGFloat postCodeBtnH = codeTfH;
    self.postCodeBtn.frame = CGRectMake(postCodeBtnX, postCodeBtnY, postCodeBtnW, postCodeBtnH);
 
    CGFloat codeViewX = phoneTfX;
    CGFloat codeViewY = CGRectGetMaxY(self.codeTf.frame) + 1;
    CGFloat codeViewW = codeTfW;
    CGFloat codeViewH = phoneViewH;
    self.codeView.frame = CGRectMake(codeViewX, codeViewY, codeViewW, codeViewH);
}
@end
